﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebBrowser
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Text = "C# Beginner to Expert - Web Browser!";

            webBrowser.Height = browserHeight();
            webBrowser.Width = browserWidth();
            webBrowser.Top = 3;
            webBrowser.Left = 3;

        }

        private void webBrowser_Resize(object sender, EventArgs e)
        {
            webBrowser.Height = browserHeight();
            webBrowser.Width = browserWidth();
        }

        // Browser functions
        private void btnBack_Click(object sender, EventArgs e)
        {
            if (webBrowser.CanGoBack)
            {
                webBrowser.GoBack();
            }
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            if (webBrowser.CanGoForward)
            {
                webBrowser.GoForward();
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (webBrowser.IsBusy)
            {
                webBrowser.Stop();
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            goToUrl();
        }

        // Helper Methods
        private int browserWidth()
        {
            return this.Width - 20;
        }

        private int browserHeight()
        {
            return this.Height - (20 + toolStrip.Height);
        }

        private void goToUrl()
        {
            // A Try statement inserted to stop the Browser crashing ..........
            // when a user enters an invalid URL eg: http:// and pressing return
            try
            {
                Uri URL = new Uri(txtURL.Text);
                webBrowser.Url = URL;
            }
            catch (Exception)
            {
                
            //    throw;
            }
        }

        private void txtURL_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                goToUrl();
            }
        }

    }
}
